﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Best.SmartCms.Utility.Common
{
    public static class StringUtility
    {
        /// <summary>
        /// 返回list long
        /// </summary>
        /// <param name="strArry"></param>
        /// <param name="splitChar"></param>
        /// <param name="strArryIsAES"></param>
        /// <returns></returns>
        public static List<long> ConvertStringToLong(string strArry, string splitChar, bool strArryIsAES = false)
        {
            var split = strArry.Split(new[] { splitChar }, StringSplitOptions.RemoveEmptyEntries);
            var result = new List<long>();
            foreach (string s in split.Where(s => !string.IsNullOrWhiteSpace(s)))
            {
                long outId;
                string str = s;
                if (strArryIsAES)
                {
                    str = AESHandler.Decrypt(s);
                }
                var flag = Int64.TryParse(str, out outId);
                if (flag)
                    result.Add(outId);
            }
            return result.Count == 0 ? null : result.Distinct().ToList();
        }

        /// <summary>
        /// 校验字符串长度是否大于预期值
        /// </summary>
        /// <param name="strArry"></param>
        /// <param name="preLength"></param>
        /// <returns></returns>
        public static bool CheckStringMaxLength(string strArry, int preLength)
        {
            if (string.IsNullOrWhiteSpace(strArry))
            {
                return false;
            }
            if (strArry.Length == 0)
                return true;
            ASCIIEncoding ascii = new ASCIIEncoding();
            int tempLen = 0;
            byte[] s = ascii.GetBytes(strArry);
            for (int i = 0; i < s.Length; i++)
            {
                if ((int)s[i] == 63)
                {
                    tempLen += 2;
                }
                else
                {
                    tempLen += 1;
                }
            }
            return tempLen > preLength;
        }

        /// <summary>
        /// <para>将 URL 中的参数名称/值编码为合法的格式。</para>
        /// <para>可以解决类似这样的问题：假设参数名为 tvshow, 参数值为 Tom&Jerry，如果不编码，可能得到的网址： http://a.com/?tvshow=Tom&Jerry&year=1965 编码后则为：http://a.com/?tvshow=Tom%26Jerry&year=1965 </para>
        /// <para>实践中经常导致问题的字符有：'&', '?', '=' 等</para>
        /// </summary>
        /// <param name="data"></param>
        /// <returns></returns>
        public static string AsUrlData(this string data)
        {
            if (data == null)
            {
                return null;
            }
            return Uri.EscapeDataString(data);
        }
    }
}
